#include "PllClockSource.h" // IWYU pragma: keep

void bsp::PllClockSource::Configure(std::string const &input_channel_name,
									std::map<std::string, uint32_t> const &channel_factor_map)
{
	ChannelFactorConfig factors{channel_factor_map};
	RCC_OscInitTypeDef def{};
	def.OscillatorType = RCC_OSCILLATORTYPE_NONE;
	def.PLL.PLLState = RCC_PLL_ON;
	def.PLL.PLLSource = get_pll_source_define(input_channel_name);
	def.PLL.PLLM = factors.M();
	def.PLL.PLLN = factors.N();
	def.PLL.PLLP = factors.P();
	def.PLL.PLLQ = factors.Q();

	HAL_StatusTypeDef result = HAL_RCC_OscConfig(&def);
	if (result != HAL_StatusTypeDef::HAL_OK)
	{
		throw std::runtime_error{"打开 PLL 失败。"};
	}

	// 打开后，记录各个输出通道的频率
	base::unit::MHz input_freq = get_input_frequency(input_channel_name);
	_p_freq = input_freq / factors.M() * factors.N() / factors.P();
	_q_freq = input_freq / factors.M() * factors.N() / factors.Q();

	_opened = true;
}
